package ldk.apps.compass

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.*
import android.hardware.SensorManager
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File

class MainActivity : Activity() {

    companion object {
        internal fun angleToChinese(angleValue: Int): String{
            return when(angleValue){
                0 -> "北"
                in 1..45 -> "北偏东$angleValue°"
                in 46..89 -> "东偏北${90 - angleValue}°"
                90 -> "东"
                in 91..135 -> "东偏南${angleValue - 90}°"
                in 136..179 -> "南偏东${180 - angleValue}°"
                180, -180 -> "南"
                in -45..-1 -> "北偏西${-angleValue}°"
                in -89..-46 -> "西偏北${90 + angleValue}°"
                -90 -> "西"
                in -135..191 -> "西偏南${-angleValue - 90}°"
                in -179..-136 -> "南偏西${180 + angleValue}°"
                else -> "不可思议的度数"
            }
        }
    }

    private val TAG = "MainActivity"

    private lateinit var compass: Compass
    private var conditionFine = false
    private var gotoSettings = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initCustomColor()
        compass = Compass(getSystemService(Context.SENSOR_SERVICE) as SensorManager)
        conditionFine = compass.findAccelerometerSensor() && compass.findMagnetometersSensor()
        if (conditionFine){
            compass.callback = {
                val angleToChinese = MainActivity.angleToChinese(it)
//                Log.v(TAG, "指南针值发生改变，$it $angleToChinese")
                tv_content.text = angleToChinese
                val currentRotation = iv_bg.rotation
                val relativeValue = -it;
                val rotation = if (relativeValue >= 0) relativeValue else 360 + relativeValue
                if (currentRotation.toInt() != rotation){
                    val delta = rotation - currentRotation
                    val rotationDeltaBy = if (Math.abs(delta) <= 180){
                        delta
                    }else{
                        if (delta > 0){
                            delta - 360
                        }else{
                            360 + delta
                        }
                    }
                    iv_bg.animate().rotationBy(rotationDeltaBy)
                }
            }
        }
        iv_edit.setOnClickListener {
            gotoSettings = true
            startActivity(Intent(this, SettingsActivity::class.java))
        }
    }

    private fun initCustomColor(){
        val bitmap = composeBitmap(SettingsActivity.getCompassColor(this))
        iv_bg.setImageBitmap(bitmap)
        tv_content.setTextColor(SettingsActivity.getFontColor(this))
        fl_root.setBackgroundColor(SettingsActivity.getBgColor(this))
    }

    private fun composeBitmap(color: Int): Bitmap{
        if (color == Color.BLACK){
            return BitmapFactory.decodeResource(resources, R.raw.bg_compass)
        }
        val outFile = File(filesDir, "compress$color.bitmap")
        if (outFile.exists()){
            return BitmapFactory.decodeFile(outFile.absolutePath)
        }
        val width = resources.displayMetrics.widthPixels
        val resultBitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(resultBitmap)
        val paint = Paint()
        val originBitmap = BitmapFactory.decodeResource(resources, R.raw.bg_compass)
        val originalBitmapShader = BitmapShader(originBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        val matrix = Matrix()
        matrix.setScale(width * 1.0f / originBitmap.width, width * 1.0f /originBitmap.height)
        originalBitmapShader.setLocalMatrix(matrix)
        val colorBitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888)
        val colorCanvas = Canvas(colorBitmap)
        colorCanvas.drawColor(color)
        val colorBitmapShader = BitmapShader(colorBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)

        paint.shader = ComposeShader(originalBitmapShader, colorBitmapShader, PorterDuff.Mode.SRC_IN)
        canvas.drawPaint(paint)

        originBitmap.recycle()
        colorBitmap.recycle()
        val outputStream = outFile.outputStream()
        resultBitmap.compress(Bitmap.CompressFormat.PNG, 90, outputStream)
        outputStream.close()
        return resultBitmap
    }

    override fun onResume() {
        super.onResume()
        if (gotoSettings){
            initCustomColor()
            gotoSettings = false
        }
        if (conditionFine)
            compass.registerListener()
    }

    override fun onPause() {
        super.onPause()
        if (conditionFine)
            compass.unRegisterListener()
    }
}
